import { T_task } from '@/obj/class/base/task/index';
import { ifs, Tsrv } from '@/services';
import { N_cScadaView } from './types';

class T_cmd {
  // 主组件箱
  private compBox: ifs.I_compBox;

  // 主组件ID
  private compID: string;

  private task: T_task = new T_task(5000);

  // 主组件实例
  private self: N_cScadaView.cScadaView;

  private ecBoxDetMap: Map<string, N_cScadaView.I_ecBoxDet> = new Map();

  private ecBoxDetCodeList: Array<string> = [];

  // 主组件created里初始化
  public init(self: N_cScadaView.cScadaView, compBoxInfo: ifs.I_compBoxInfo) {
    this.self = self;
    this.compBox = compBoxInfo.TcompBox;
    this.compID = compBoxInfo.compID;
  }

  public getTcmd(): T_cmd {
    return this;
  }

  public getEcBoxDetMap(): Map<string, N_cScadaView.I_ecBoxDet> {
    return this.ecBoxDetMap;
  }

  public setEcBoxDetMap(ecBoxDetCode: string, value: N_cScadaView.I_ecBoxDet) {
    this.ecBoxDetMap.set(ecBoxDetCode, value);
    this.ecBoxDetCodeList.push(ecBoxDetCode);
  }

  public cleanEcBoxDetMap() {
    this.ecBoxDetMap.clear();
    this.ecBoxDetCodeList = [];
  }

  public startTask() {
    this.task.addTask(this.readData);
    this.task.startTask();
  }

  public stopTask() {
    this.task.stopTask();
  }

  // 读取单次数据
  public readDataOnce(codes: string[]) {
    Tsrv.standardPostReq<N_cScadaView.I_readResp, any>(
      { ecDetCodes: codes },
      Tsrv.url.scadaRead
    ).then(([readResp, err]) => {
      if (!Tsrv.noValue(err)) {
        this.self.$msg(err);
        return;
      }
      if (!readResp.success) {
        this.self.$msg(readResp.msg);
        return;
      }
      const keys = Object.keys(readResp.data);
      keys.forEach(k => {
        if (this.ecBoxDetMap.has(k)) {
          this.ecBoxDetMap.get(k).val = `${readResp.data[k].v}`;
          this.ecBoxDetMap.get(k).timestamp = `${readResp.data[k].timestamp}`;
          this.ecBoxDetMap.get(k).err = `${
            readResp.data[k].err === null ? '' : readResp.data[k].err
          }`;
        }
      });
    });
  }

  private readData = () => {
    Tsrv.standardPostReq<N_cScadaView.I_readResp, any>(
      { ecDetCodes: this.ecBoxDetCodeList },
      Tsrv.url.scadaRead
    ).then(([readResp, err]) => {
      if (!Tsrv.noValue(err)) {
        this.self.$msg(err);
        return;
      }
      if (!readResp.success) {
        this.self.$msg(readResp.msg);
        return;
      }
      const keys = Object.keys(readResp.data);
      keys.forEach(k => {
        if (this.ecBoxDetMap.has(k)) {
          this.ecBoxDetMap.get(k).val = `${readResp.data[k].v}`;
          this.ecBoxDetMap.get(k).timestamp = `${readResp.data[k].timestamp}`;
          this.ecBoxDetMap.get(k).err = `${
            readResp.data[k].err === null ? '' : readResp.data[k].err
          }`;
        }
      });
    });
  };
}
interface I_cmd extends T_cmd {}
export { I_cmd, T_cmd };
